//发起解散
module.exports = function() {
	this.state = false 		//解散状态
	this.dissolutionPlayer = 0
	this.agreeList = {}
	this.refuseList = {}
	var local = {}
	local.timer = 0
	local.TIME = 15000
	local.beginTime = 0
	//发起解散
	this.handle.dissolution = function(uid,sid,param,cb){
		if(this.state){
			cb(false)
			return
		}
		this.state = true
		this.agreeList[uid] = true
		this.dissolutionPlayer = uid
		local.beginTime = (new Date()).getTime()
		var notify = {
			cmd : "dissolution",
			uid : uid,
			timeRemaining : local.TIME
		}
		this.sendAll(notify)
		local.timer = setTimeout(local.success.bind(this),local.TIME)
		local.check.apply(this)
		cb(true)
	}
	//同意解散
	this.handle.agreeDissolve = function(uid,sid,param,cb){
		if(!this.state){
			cb(false)
			return
		}
		if(this.agreeList[uid] || this.refuseList[uid]){
			cb(false)
			return
		}
		this.agreeList[uid] = true
		var notify = {
			cmd : "agreeDissolve",
			uid : uid
		}
		this.sendAll(notify)
		cb(true)
		local.check.apply(this)
	}
	//拒绝解散
	this.handle.refuseDissolve = function(uid,sid,param,cb){
		if(!this.state){
			cb(false)
			return
		}
		if(this.agreeList[uid] || this.refuseList[uid]){
			cb(false)
			return
		}
		this.refuseList[uid] = true
		var notify = {
			cmd : "refuseDissolve",
			uid : uid
		}
		this.sendAll(notify)
		cb(true)
		local.check.apply(this)
	}
	//获取解散状态
	this.handle.getDissolutionInfo = function(uid,sid,param,cb) {
		var info = {
			state : this.state,
			agreeList : this.agreeList,
			refuseList : this.refuseList,
			dissolutionPlayer : this.dissolutionPlayer,
			timeRemaining : local.beginTime + local.TIME - (new Date()).getTime()
		}
		if(info.timeRemaining < 0){
			info.timeRemaining = 0
		}
		cb(true,info)
	}
	//检查  半数以上同意则解散、半数及以下则取消
	local.check = function() {
		var allCount = 0
		this.forEachActive(function() {
			allCount++
		})
		var agreeCount = 0
		for(var i in this.agreeList){
			agreeCount++
		}
		var refuseCount = 0
		for(var i in this.refuseList){
			refuseCount++
		}
		if(agreeCount > allCount / 2){
			local.success.apply(this)
		}else if(refuseCount >= allCount / 2){
			local.failure.apply(this)
		}
	}
	//解散成功
	local.success = function() {
		clearTimeout(local.timer)
		var notify = {
			cmd : "dissolveSuccess"
		}
		this.sendAll(notify)
		this.gameOverBefore()
	}
	//解散失败
	local.failure = function() {
		clearTimeout(local.timer)
		var notify = {
			cmd : "dissolveFailure"
		}
		this.sendAll(notify)
		this.state = false 		//解散状态
		this.agreeList = {}
		this.refuseList = {}
		this.dissolutionPlayer = 0
	}
}